package com.metrics.extractors;

import java.text.ParseException;
import java.util.*;

import org.jfree.data.time.RegularTimePeriod;

import com.database.daos.IMaxDao;
import com.database.objects.*;
import com.load.utils.DateUtil;
import com.metrics.formatters.TimeFormatter;

public class MetricCyclomaticComplexityExtractor extends MetricExtractor {

	private static final long serialVersionUID = -2295309662790532125L;

	private IMaxDao maxDao;

	@Override
	public Double extract(Developer developer, Type type, Status status, String start, String finish) {
		return maxDao.getMaxCyclomaticContributionsByDeveloperAndTypeAndStatus(developer, type, status, start, finish);
	}

	@Override
	public Double extract(Developer developer, String date, Type type, Status status) {
		Contribution contribution = contributionDao.getByDeveloperAndDateAndTypeAndStatus(developer, date, type, status);
		return contribution != null ? contribution.getCyclomatic() : 0.0;
	}

	@Override
	public Double extractTotal(Project project, Type type, Status status, String start, String finish) {
		return maxDao.getMaxCyclomaticContributionsByProjectAndTypeAndStatus(project, type, status, start, finish);
	}

	@Override
	public Map<RegularTimePeriod, Double> extractWithDate(Developer developer, Type type, Status status, String start, String finish, TimeFormatter formatter) {
		Map<RegularTimePeriod, Double> map = new HashMap<RegularTimePeriod, Double>();
		List<Contribution> contributions = contributionDao.findByDeveloperAndTypeAndDate(developer, type, status, start, finish);
		for (Contribution contribution : contributions) {
			try {
				Date date = DateUtil.formatDate(contribution.getDate());
				RegularTimePeriod period = formatter.format(date);
				if (map.containsKey(period)) {
					map.put(period, map.get(period) + contribution.getCyclomatic());
				} else {
					map.put(period, contribution.getCyclomatic());
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	public void setMaxDao(IMaxDao maxDao) {
		this.maxDao = maxDao;
	}

}